<?php

echo "Master process id" . posix_getpid() . PHP_EOL;

$childs = [];

function fork () {
    global $childs;

    $pid = pcntl_fork();
    switch ($pid) {
        case -1:
            exit('进程创建错误' . PHP_EOL);
            break;
        case 0:
            // 子进程
            echo "子进程 进程id：" . posix_getpid() . PHP_EOL;
            while (true) {
                // echo posix_getpid() . '子进程正在工作' . PHP_EOL;
                sleep(3);
            }
            break;
        default:
            // 父进程
            $childs[$pid] = $pid;
            break;
    }
}

$count = 3;
for ($i = 0; $i < $count; $i++) {
    fork();
}

while (count($childs) > 0) {
    $exitId = pcntl_wait($status);
    if ($exitId > 0) {
        echo "子进程id" . $exitId . '退出了' . PHP_EOL;
        $value = pcntl_wtermsig($status);
        echo "中断进程信号的值为: " . $value . PHP_EOL;
        unset($childs[$exitId]);
    }

    if (count($childs) < $count) {
        fork();
    }
}

echo "主进程退出了..." . PHP_EOL;